import httpUtil from "@/utils/httpUtil";
import deviceUtil from "../utils/deviceUtil";
// // #ifdef H5
// import * as jweixin from 'weixin-js-sdk'
// // #endif
import messageUtil from "../utils/messageUtil";
import userApi from "./userApi";

const requestStatus = (params, backMethod) => {
	return httpUtil.post("/api/rf/status", params, backMethod);
}

/**
 * 
 */
const submitOrder = (mobile, successCallBack, failCallBack) => {
	// type 类型:1=支付宝小程序,2=微信外h5[外部浏览器],3=微信小程序,5=微信内h5[公众号js支付],4=支付宝h5[目前看支付宝内外通用]
	// #ifdef H5
	// 类型:1=支付宝小程序,2=微信h5,3=微信小程序,4=支付宝h5，默认4，目前该接口用于支付宝h5付款
	// let type = 2
	// let quit_url = location.href;
	// let params = {
	// 	mobile,
	// 	quit_url,
	// 	type,
	// }
	if (deviceUtil.isAliBrowser()) {
		h5SubmitOrder(mobile, location.href, 4)
	} else if (deviceUtil.isWeChatBrowser()) {
		h5WeChatSubmitOrder(mobile, successCallBack, failCallBack)
	} else {
		h5SubmitOrder(mobile, location.href, 2)
	}

	// #endif

	// #ifdef MP-ALIPAY
	zfbMiniSubmitOrder(mobile, successCallBack, failCallBack)
	// #endif
	// #ifdef MP-WEIXIN
	wxMiniSubmitOrder(mobile, successCallBack, failCallBack)
	// #endif
}

const h5WeChatSubmitOrder = (mobile, successCallBack, failCallBack) => {
	let params = {
		mobile,
		quit_url: location.href,
		type: 5,
		ordertype: 6,
		a: httpUtil.getA(),
		openid: userApi.getUserId()
	}
	// if (userApi.getUserId()) {
	// 	params.user_id = userApi.getUserId()
	// }
	if (userApi.getParam()) {
		params.param = userApi.getParam()
	}
	return httpUtil.post("/api/rf/hjkCreatePayNew", params, res => {
		console.log('h5WeChatSubmitOrder', res)
		// // 现在默认是微信支付微信返回的是html 所以直接渲染
		// document.write(res.data);
		// document.close();
		h5WeChatPayHandler(res.data, successCallBack, failCallBack)
	});
}

const h5WeChatPayHandler = (payRes, successCallBack, failCallBack) => {
	jweixin.config({
		debug: false,
		appId: payRes.appId, // 必填，公众号的唯一标识
		timestamp: payRes.timeStamp, // 必填，生成签名的时间戳
		nonceStr: payRes.nonceStr, // 必填，生成签名的随机串
		signature: payRes.paySign,
		jsApiList: ['chooseWXPay']
	});

	jweixin.ready(function() {
		jweixin.checkJsApi({
			jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
			success: function(res) {
				console.log('checkjsapi  Success');
				console.log(res);
			},
			fail: function(res) {
				console.log('checkJsApi fail res');
				console.log(res);
			}
		});

		jweixin.chooseWXPay({
			timestamp: payRes.timeStamp,
			nonceStr: payRes.nonceStr, // 支付签名随机串，不长于 32 位
			package: payRes.package,
			signType: payRes.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
			paySign: payRes.paySign, // 支付签名
			success(res) {
				console.log('h5WeChatPayHandler chooseWXPay success:' + JSON.stringify(res));
				if (successCallBack) {
					successCallBack(res);
				}

			},
			fail(res) {
				console.log('h5WeChatPayHandler chooseWXPay 失败res', res)
				messageUtil.closeLoading()
				messageUtil.showFail('支付失败，请于管理员联系！')
				if (failCallBack) {
					failCallBack(res);
				}
			},
			cancel: function(res) {
				console.log('h5WeChatPayHandler chooseWXPay cancel', res)
				messageUtil.closeLoading()
				messageUtil.showFail('未完成支付！')
			},
		});
	})

}

/**
 * 微信小程序下单支付
 */
const wxMiniSubmitOrder = (mobile, successCallBack, failCallBack) => {
	let params = {
		mobile,
		type: 3, // 类型:1=支付宝小程序,2=微信外h5[外部浏览器],3=微信小程序,5=微信内h5[公众号js支付],4=支付宝h5[目前看支付宝内外通用]
		ordertype: userApi.getOrderType(), // 订单类型，上线之后新版本必传，订单类型:1=通用,2=速停车,3=芝麻GO,5=快手直播,6=P云PP停车
		openid: userApi.getUserId(),
		param: userApi.getParam(),
		a: httpUtil.getA(),
		buyType: userApi.getBuyType(),
		pType:"1"
	}
	return httpUtil.post("/api/rf/hjkCreatePayYb", params, res => {
		console.log('wxMiniSubmitOrder', res)
		wxMiniPayHandler(res.data, successCallBack, failCallBack)
	});
}


const wxMiniPayHandler = (payRes, successCallBack, failCallBack) => {
	uni.getProvider({
		service: 'payment',
		success: res => {
			console.log(payRes,'payres');
			console.log(res,'res');
			
			uni.requestPayment({
				provider: res.provider[0],
				timeStamp: JSON.parse(payRes.payUrl).timeStamp,
				nonceStr:JSON.parse(payRes.payUrl).nonceStr,
				package:JSON.parse(payRes.payUrl).package,
				signType:JSON.parse(payRes.payUrl).signType,
				paySign:JSON.parse(payRes.payUrl).paySign,
				success: (successRes) => {
					// {"result":"","resultCode":"6001","callbackUrl":"","memo":"支付未完成","extendInfo":{},"errMsg":"requestPayment:ok"}
					console.log('wxMiniPayHandler requestPayment success:' + JSON.stringify(
						successRes));
					if (successCallBack) {
						successCallBack(successRes)
					}

				},
				fail: (err) => {
					console.log('wxMiniPayHandler requestPayment fail:' + JSON.stringify(
						err));
					if (failCallBack) {
						failCallBack(err)
					}
				}
			})
		},
		fail: res => {
			console.log('wxMiniPayHandler getProvider fail', res);
		}
	})
}

const zfbMiniSubmitOrder = (mobile, successCallBack, failCallBack) => {
	let params = {
		mobile,
		type: 1
	}
	return httpUtil.post("/api/rf/hjkCreatePayNew", params, res => {
		console.log('zfbMiniSubmitOrder', res)
		zfbMiniPay(res.data.trade_no, successCallBack, failCallBack)
	});
}

const h5SubmitOrder = (mobile, quit_url, type) => {

	let a = httpUtil.getA()
	let params = {
		mobile,
		quit_url,
		type,
		ordertype: 6, // 订单类型，上线之后新版本必传，订单类型:1=通用,2=速停车,3=芝麻GO,5=快手直播,6=P云PP停车
		a
	}
	if (userApi.getUserId()) {
		params.user_id = userApi.getUserId()
	}
	if (userApi.getParam()) {
		params.param = userApi.getParam()
	}

	return httpUtil.post("/api/rf/hjkCreatePayNew", params, res => {
		console.log('h5SubmitOrder', res)
		// 支付宝h5
		if (params.type == 4) {
			window.location.href = res.data.payUrl
		} else {
			// 现在默认是微信支付微信返回的是html 所以直接渲染
			document.write(res.data);
			document.close();
		}

	});

}

const zfbMiniPay = (tradeNo, successCallBack, failCallBack) => {
	uni.getProvider({
		service: 'payment',
		success: res => {
			console.log('getProvider success', res, tradeNo);
			console.log(res.provider[0]);
			uni.requestPayment({
				provider: res.provider[0],
				orderInfo: tradeNo,
				success: (successRes) => {
					// {"result":"","resultCode":"6001","callbackUrl":"","memo":"支付未完成","extendInfo":{},"errMsg":"requestPayment:ok"}
					console.log('requestPayment success:' + JSON.stringify(successRes));
					if (successRes.resultCode == 6001) {
						messageUtil.closeLoading()
						messageUtil.showFail('支付失败')
						return;
					}
					if (successCallBack) {
						successCallBack(successRes)
					}

				},
				fail: (err) => {
					console.log('requestPayment fail:' + JSON.stringify(err));
					if (failCallBack) {
						failCallBack(err)
					}
				}
			})
		},
		fail: res => {
			console.log('getProvider fail', res);
		}
	})
}

/**
 * 状态:0=支付失败,1=支付成功,-1=未付款,all=全部，默认all，传字符串
 */
const getOrderList = (callBack, status = 1) => {
	let params = {
		openid: uni.getStorageSync('openids'),
		status,
		page: 1,
	}

	httpUtil.post('/api/rf/hjkGetOrder', params, res => {
		if (callBack) {
			callBack(res)
		}
	})
}

const setParam = (param) => {
	uni.setStorageSync('param', param)
}

const getParam = () => {
	return uni.getStorageSync('param');
}

/**
 *  存量包下单接口
 */
const submitClbOrder = (pid, mobile, smsCode, infoOrderNum, successCallBack, failCallBack) => {
	let params = {
		pid,
		mobile,
		smsCode,
		infoOrderNum,
		a: httpUtil.getA(),
	}
	if (getParam()) {
		params.param = getParam()
	}
	console.log('submitClbOrder', getIdentity())
	if (getIdentity()) {
		params.identity = getIdentity()
	}
	if (getAppId()) {
		params.app_id = getAppId()
	}
	if (getNickname()) {
		params.nickname = getNickname()
	}
	if (getOpenid()) {
		params.openid = getOpenid()
	}
	return httpUtil.post("/api/Clb/placeOrder", params, res => {
		if (successCallBack) {
			successCallBack(res)
		}
	}, errRes => {
		console.log(errRes)
		if (failCallBack) {
			failCallBack(errRes)
		}
	})
}

// pp 停车需要的参数
const setIdentity = (identity) => {
	uni.setStorageSync('identity', identity)
}

const getIdentity = () => {
	return uni.getStorageSync('identity');
}
// pp 停车需要的参数
const setAppId = (app_id) => {
	uni.setStorageSync('app_id', app_id)
}

const getAppId = () => {
	return uni.getStorageSync('app_id');
}
// pp 停车需要的参数
const setNickname = (nickname) => {
	uni.setStorageSync('nickname', nickname)
}

const getNickname = () => {
	return uni.getStorageSync('nickname');
}

// pp 停车需要的参数
const setOpenid = (openid) => {
	uni.setStorageSync('openid', openid)
}

const getOpenid = () => {
	return uni.getStorageSync('openid');
}

export default {
	requestStatus,
	submitOrder,
	getOrderList,
	submitClbOrder,
	setParam,
	getParam,
	setIdentity,
	getIdentity,
	setAppId,
	getAppId,
	setNickname,
	getNickname,
	setOpenid,
	getOpenid,
}